package com.my.netty.promote.server.handler;

import com.my.netty.promote.message.GroupCreateRequestMessage;
import com.my.netty.promote.message.GroupCreateResponseMessage;
import com.my.netty.promote.server.session.Group;
import com.my.netty.promote.server.session.GroupSession;
import com.my.netty.promote.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.Set;

@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage message) throws Exception {
        String groupName = message.getGroupName();
        Set<String> members = message.getMembers();
        //创建群
        GroupSession groupSession = GroupSessionFactory.getSession();
        Group group = groupSession.createGroup(groupName, members);
        if (group == null) {
            //创建成功
            ctx.writeAndFlush(new GroupCreateResponseMessage(true, groupName + "创建成功"));
            //向群内所有人发一个拉群消息，先获取所有在线者channel
            List<Channel> membersChannel = groupSession.getMembersChannel(groupName);
            for (Channel channel : membersChannel) {
                channel.writeAndFlush(new GroupCreateResponseMessage(true, "您已被拉入" + groupName));
            }
        } else {
            //创建失败，已有该群名
            ctx.writeAndFlush(new GroupCreateResponseMessage(false, groupName + "创建失败，群已经存在"));
        }
    }
}
